package com.tzl.config;

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {
	public AgeRoutePredicateFactory() {
		super(Config.class);
	}
	//判断请求中的age参数是否在指定范围内
	@Override
	public Predicate<ServerWebExchange> apply(Config config) {
		return exchange -> {
			String ageStr = exchange.getRequest().getQueryParams().getFirst("age");
			if (StrUtil.isNotBlank(ageStr)) {
				int age = Integer.parseInt(ageStr);
				return age >= config.getMinAge() && age <= config.getMaxAge();
			}
			return false;
		};
	}
	//返回配置字段的顺序
	@Override
	public List<String> shortcutFieldOrder() {
		return Arrays.asList("minAge", "maxAge");
	}
	@Data
	@NoArgsConstructor
	public static class Config {
		private Integer minAge; // 最小年龄
		private Integer maxAge; // 最大年龄
	}
}
